package com.simon.study.algorithm.leetcode;

/**
 * <p>
 *
 * @author simon
 */
public class AddTwoNumbers00002 {


    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
    }

    public static ListNode solution(ListNode n1, ListNode n2){
        ListNode cur1 = n1, cur2 = n2, rst = new ListNode(0), cur3 = rst, prev = cur3;
        while (cur1 != null && cur2 !=null){
            cur3.val =  cur3.val + cur1.val + cur2.val;

            if( cur3.val >= 10 ){
                cur3.val = cur3.val % 10;
                cur3.next = new ListNode(1);
            }else{
                cur3.next = new ListNode(0);
            }
            cur1 = cur1.next; cur2 = cur2.next; prev = cur3; cur3 = cur3.next;
        }

        while (cur1 != null){
            cur3.val = cur3.val + cur1.val;
            if(cur3.val >= 10){
                cur3.val = cur3.val % 10; cur3.next = new ListNode( 1);
            }else{
                cur3.next = new ListNode(0);
            }
            cur1 = cur1.next;
            prev = cur3;
            cur3 = cur3.next;
        }

        while (cur2 != null){
            cur3.val = cur3.val + cur2.val;
            if(cur3.val >= 10){
                cur3.val = cur3.val % 10; cur3.next = new ListNode( 1);
            }else{
                cur3.next = new ListNode(0);
            }
            cur2 = cur2.next;
            prev = cur3;
            cur3 = cur3.next;
        }

        if(cur3.val  == 0){ prev.next = null; }

        return rst;
    }
}
